<?php
/**
 * Created by PhpStorm.
 * User: crazy
 * Date: 2018/12/12
 * Time: 13:29
 */

namespace app\api\logic;

use app\api\facade\TokenService;
use app\api\model\Article;
use app\api\model\Category;
use app\api\model\Pms;
use app\lib\enum\MobileEnum;
use think\facade\Config;

/**
 * 手机应用逻辑层
 *
 * @package app\api\logic
 */
class Mobile {
    /**
     * 根据令牌获取该用户站内信
     *
     * @param string $token 令牌
     *
     * @return Pms[]|false
     * @throws \think\Exception\DbException
     */
    public function getUserNewMessagesByToken($token) {
        $uid = TokenService::getUserIdByToken($token);
        $where = [
            'pm_receiver_id' => $uid,
            'pm_status' => MobileEnum::MESSAGE_STATUS_NEW
        ];
        $messages = Pms::all($where);
        return $messages;
    }

    /**
     * 获取最新消息
     *
     * @return array|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNewArticles() {
        $limit = Config::get('global.news_num');
        $order = [
            'art_top' => 'desc',
            'art_order' => 'desc',
            'art_publishtime' => 'desc'
        ];
        $field = [
            'id',
            'art_title',
            'art_description',
            'art_author',
            'art_publishtime',
            'art_thumb',
            'art_click'
        ];
        $articles = Article::field($field)->order($order)->limit($limit)->select();
        return $articles;
    }

    /**
     * 按id获取文章信息
     *
     * @param int $id 文章id
     *
     * @return Article|null
     * @throws \think\Exception\DbException
     */
    public function getArticleById($id) {
        return Article::get($id);
    }

    /**
     * 获取所有可以显示的文章分类
     *
     * @return Category[]|false
     * @throws \think\Exception\DbException
     */
    public function getAllCategories() {
        return Category::order('cat_order DESC')->all(['cat_show' => MobileEnum::CATEGORY_SHOW]);
    }

    public function getArticlesByCategoryId($cid) {
        $articleModle = new Article();
        $order = [
            'art_top' => 'desc',
            'art_order' => 'desc',
            'art_publishtime' => 'desc'
        ];
        $articles = $articleModle->where('category_id', '=', $cid)
            ->order($order)
            ->paginate(10, true);
        return $articles;
    }
}